﻿using Forum.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Forum.Models;
using ForumBL;

namespace Forum.Controllers
{

    public class SectionController : Controller
    {
        public ActionResult Index()
        {       
            SectionBL sectionContext = new SectionBL();
            CategoryBL categoryContext = new CategoryBL();
            List<ForumDomainModels.Section> sections = sectionContext.GetAllSections();
            List<SectionsWithCategories> sectionModels = new List<SectionsWithCategories>();
            foreach (var item in sections)
            {
                Forum.Models.SectionsWithCategories currentSection =
                    new Forum.Models.SectionsWithCategories();
                currentSection.section = item;
                List<ForumDomainModels.Category> categoriesToSection =
                    categoryContext.GetCategoriesBySection(currentSection.section);
                currentSection.categories = this.FillCategoriesInfo(categoriesToSection);
                sectionModels.Add(currentSection);
            }
            return View(sectionModels);
        }

        private List<CategoryModel> FillCategoriesInfo(List<ForumDomainModels.Category> categories)
        {
            List<CategoryModel> categoryModels = new List<CategoryModel>();
            foreach (var item in categories)
            {
                CategoryModel currentCategoryModel = new CategoryModel();
                currentCategoryModel.CategoryId = item.Id;
                currentCategoryModel.CategoryName = item.CategoryName;
                currentCategoryModel.Description = item.Description;
                currentCategoryModel.LastPostTime = LastPostTimeinCategory(item);
                currentCategoryModel.PostCount = PostCountByCategory(item);
                categoryModels.Add(currentCategoryModel);
            }
            return categoryModels;
        }


        private DateTime LastPostTimeinCategory(ForumDomainModels.Category category)
        {
            CategoryBL categoryContext = new CategoryBL();
            DateTime lastPostTime = categoryContext.LastPostTimeInCategory(category);
            return lastPostTime;
        }


        private int PostCountByCategory(ForumDomainModels.Category category)
        {
            PostBL postContext = new PostBL();
            int postCount = postContext.GetPostCountByCategory(category);
            return postCount;
        }


    }
}
